/*
 * @Descripttion: 
 * @version: V1.0.0
 * @Author: LeonHe
 * @Date: 2021-10-17 01:22:54
 * @LastEditTime: 2021-10-31 00:02:52
 */

#include "key.h"
#include "gpio.h"
#include "time.h"
#include "string.h"
#include "stdio.h"

#include "atom.h"
#include "atomport-private.h"

stKeyEvenDef gStKeyEvent[6] = {0};

uint8_t keyValue[6] = {0};
uint8_t keyValueLast[6] = {0};

static stTimeObjDef timePress[6] = {0};

static void keyValueUpdate(void)
{
    keyValue[0] = GPIO_KEY_POWER; 
    keyValue[1] = GPIO_KEY_ADD;   
    keyValue[2] = GPIO_KEY_SUB;   
    keyValue[3] = GPIO_KEY_SETT;  
    keyValue[4] = GPIO_KEY_CLEAR; 
    keyValue[5] = GPIO_KEY_MOTO;  
}

void keyInit(void)
{
    keyValueUpdate();
    memcpy(keyValueLast, keyValue, sizeof(keyValue));
}

void keyScan(void)
{
    uint8_t i = 0;

    for(i = 0; i < 6; i++)
    {
        keyValueUpdate();
        if(keyValue[i] != keyValueLast[i])
        {
            atomTimerDelay(20);
            keyValueUpdate();
            if(keyValue[i] != keyValueLast[i])
            {
                keyValueLast[i] = keyValue[i];
                if(!keyValue[i])
                {
                    timeCoutStart(&timePress[i], 3000);
                }
                else 
                {
                    if(!timePress[i].isTimeOut)
                    {
                        // printf("key %d pressed!\r\n", (uint16_t)i);
                        gStKeyEvent[i].pressed = 1;
                    }
                }
            }
        }
        else
        {
            if(!keyValue[i])
            {
                if(!timePress[i].isTimeOut && timeIsTimeOut(&timePress[i]))
                {
                    gStKeyEvent[i].longPressed = 1;
                }
            }
        }
    }
}

